package cn.cloudtogo.server.module;

import cn.cloudtogo.common.GendbException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;

import static cn.cloudtogo.common.GendbGlobalConstant.SCHEMA_SYSTEM;

/**
 * @author yaolianhua789@gmail.com
 **/
@Component
@Slf4j
public class BuiltInTableCreator {


    private final JdbcTemplate jdbcTemplate;

    public BuiltInTableCreator(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @PostConstruct
    public void schema() {
        String schemaSql = String.format("create schema if not exists %s", SCHEMA_SYSTEM);
        jdbcTemplate.execute(schemaSql);
//        log.debug("execute sql '{}'", schemaSql);
    }

    public void createExternalDatasourceTable() {

        Path path = Paths.get(System.getProperty("user.dir"), "mysql", "external_datasource.sql");
//        log.debug("Execute init sql path '{}'", path);
        if (!Files.isRegularFile(path)) {
            throw new GendbException("Get external_datasource.sql file error");
        }
        try {
            FileInputStream fileInputStream = new FileInputStream(path.toFile());
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
            String tableSql = reader.lines().collect(Collectors.joining("\n"));

//            log.debug("execute sql \n {}", tableSql);
            jdbcTemplate.execute(tableSql);

        } catch (Exception e) {
            log.error("Create table external_datasource error. '{}'", e.getMessage(), e);
            throw new GendbException("Create table external_datasource error");
        }

    }

    public void createTokenManagerTable() {

        Path path = Paths.get(System.getProperty("user.dir"), "mysql", "api_token.sql");
//        log.debug("Execute init sql path '{}'", path);
        if (!Files.isRegularFile(path)) {
            throw new GendbException("Get api_token.sql file error");
        }
        try {
            FileInputStream fileInputStream = new FileInputStream(path.toFile());
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
            String tableSql = reader.lines().collect(Collectors.joining("\n"));

//            log.debug("execute sql \n {}", tableSql);
            jdbcTemplate.execute(tableSql);

        } catch (Exception e) {
            log.error("Create table api_token error. '{}'", e.getMessage(), e);
            throw new GendbException("Create table api_token error");
        }

    }


}
